import logging
import os
import socket
import platform
from logging import handlers
from datetime import datetime

class Logger:
    def __init__(self,name = __name__):
        # 创建一个logger
        hostname = socket.gethostname()
        self.__name = name
        self.logger = logging.getLogger(self.__name)
        self.logger.setLevel(logging.DEBUG)

        if platform.system() == 'Linux':
            try:
                if os.path.exists('/tmp') is False:
                    os.mkdir("/tmp")
                if os.path.exists("/tmp/messageDB") is False:
                    os.mkdir("/tmp/messageDB")
            except:
                print("创建日志文件时出错")
            logname = "/tmp/messageDB/testCase.log"
        else:
            parent = os.path.abspath(os.path.join(str(os.path.dirname(__file__)),os.pardir))
            parent = os.path.abspath(os.path.join(str(parent),os.pardir))
            logdir = os.path.join(parent,"logs")
            if os.path.exists(logdir) is False:
                os.mkdir(logdir)
            timestr = datetime.now().strftime("%Y%m%d%H%M%S.%f")
            logname = os.path.join(logdir,f"{timestr}testCase.log")
        try:
            # 每天最多有两个日志文件，超过2个会删除
            fh = handlers.TimedRotatingFileHandler(logname,when='D',backupCount=2,encoding='utf-8')
        except:
            fh = handlers.TimedRotatingFileHandler(logname,when='D',backupCount=2,encoding='utf-8')
        fh.setLevel(logging.DEBUG)
        ch = logging.StreamHandler()
        ch.setLevel(logging.DEBUG)
        # 定义handler的输出格式
        formatter = logging.Formatter("%(asctime)s-[RUNNER-" + hostname + "]-%(filename)s--[line:%(lineno)d]-%(levelname)s: %(message)s",
                          datefmt="%m-%d %H:%M:%S")
        fh.setFormatter(formatter)
        ch.setFormatter(formatter)
        # 给logger添加handler
        self.logger.addHandler(fh)
        self.logger.addHandler(ch)
    @property
    def get_log(self):
        return self.logger

log = Logger(__name__).get_log


